<template>
  <!-- 修改密码 表单 -->
  <a-modal
    v-model:open="visible"
    title="修改密码"
    class="addStation"
    destroyOnClose
    :width="420"
    @cancel="cancel"
    centered
    :maskClosable="false"
    :closable="!props.force"
  >
    <span v-if="props.force" style="color: red; font-size: 12px"
      >应安全法规要求，需先修改密码才能继续使用系统</span
    >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
    >
      <a-form-item label="旧密码：" name="password">
        <a-input-password
          v-model:value="form.password"
          type="password"
          class="formInput"
          placeholder="请输入旧密码"
        />
      </a-form-item>
      <a-form-item label="新密码：" name="newPassWord">
        <a-input-password
          v-model:value="form.newPassWord"
          type="password"
          class="formInput"
          placeholder="请输入新密码"
        />
      </a-form-item>
      <a-form-item label="确认密码：" name="confirmPassword">
        <a-input-password
          v-model:value="form.confirmPassword"
          type="password"
          class="formInput"
          placeholder="请再次输入新密码"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel" v-if="!props.force">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确定</a-button
        >
      </div>
    </template>
  </a-modal>
</template>

<script setup>
import router from "@/router"
import secret from "@/utils/secret"
const $api = inject("$api")
const props = defineProps({
  changePasswordVisible: {
    type: Boolean,
    default: false,
  },
  userId: {
    type: Number,
    default: null,
  },
  force: {
    type: Boolean,
    default: false,
  },
})

const loading = ref(false)
const visible = ref(props.changePasswordVisible)
const formRef = ref()
const labelCol = { style: { width: "100px" } }

const emits = defineEmits(["update:changePasswordVisible"])

watch(
  () => [props.changePasswordVisible, props.userId],
  ([val, val2]) => {
    console.log(val, val2)
    visible.value = val
    if (val && val2) {
      form.value = {
        id: val2,
        password: "",
        newPassWord: "",
        confirmPassword: "",
      }
    }
  }
)

const form = ref({
  id: null,
  password: "",
  newPassWord: "",
  confirmPassword: "",
})

const validateConfirmPassword = async (rule, value) => {
  if (!value) {
    return Promise.reject("请再次输入新密码")
  }
  if (value !== form.value.newPassWord) {
    return Promise.reject("两次输入的密码不一致")
  }
  return Promise.resolve()
}

// 新增密码复杂度验证函数
const validatePasswordComplexity = async (rule, value) => {
  if (!value) {
    return Promise.reject("请输入新密码")
  }

  // 检查密码长度
  if (value.length < 8) {
    return Promise.reject("密码长度至少为8位")
  }

  // 定义字符类型正则
  const hasLowerCase = /[a-z]/.test(value)
  const hasUpperCase = /[A-Z]/.test(value)
  const hasNumbers = /[0-9]/.test(value)
  const hasSymbols = /[~！@#$%^&*()_<>]/.test(value)

  // 计算包含的字符类型数量
  let typeCount = 0
  if (hasLowerCase || hasUpperCase) typeCount++ // 字母类型
  if (hasNumbers) typeCount++ // 数字类型
  if (hasSymbols) typeCount++ // 符号类型

  if (typeCount < 2) {
    return Promise.reject("密码必须包含字母、数字、符号中的至少两种")
  }

  return Promise.resolve()
}

const rules = {
  password: [
    {
      required: true,
      message: "请输入旧密码",
      trigger: "blur",
    },
  ],
  newPassWord: [
    {
      required: true,
      validator: validatePasswordComplexity,
      trigger: "blur",
    },
  ],
  confirmPassword: [
    {
      required: true,
      validator: validateConfirmPassword,
      trigger: "blur",
    },
  ],
}

const cancel = () => {
  emits("update:changePasswordVisible", false)
}

const handleSubmit = async () => {
  await formRef.value.validate()
  loading.value = true
  form.value.password = secret.encrypt(form.value.password)
  form.value.newPassWord = secret.encrypt(form.value.newPassWord)
  const { confirmPassword, ...other } = form.value
  const res = await $api.updatePwd(other)
  if (res?.code === 0) {
    message.success("密码修改成功")
    router.push("/login")
    cancel()
  }
  loading.value = false
}
</script>

<style scoped>
.formInput {
  width: 240px !important;
}
.footerBar {
  text-align: right;
}
.footerBar button {
  margin-left: 8px;
}
:deep(.ant-form-item) {
  margin-top: 15px;
}
</style>
